import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { orderApi } from '../services/api';

export function useEditOrderForm() {
  // 表单数据
  const formData = reactive({
    customer_name: '',
    customer_phone: '',
    order_time: '',
    items: []
  });

  // 订单ID
  const orderId = ref(null);
  
  // 表单加载状态
  const loading = ref(false);
  const loadingData = ref(false);

  // 商品项表单
  const itemForm = reactive({
    name: '',
    quantity: 1,
    price: 0
  });

  // 加载订单数据
  const loadOrderData = async (id) => {
    if (!id) return false;
    
    loadingData.value = true;
    try {
      const response = await orderApi.getOrderDetail(id);
      
      if (response && response.id) {
        orderId.value = response.id;
        formData.customer_name = response.customer_name || '';
        formData.customer_phone = response.customer_phone || '';
        formData.order_time = response.order_time || new Date().toISOString();
        
        // 处理items字段
        if (typeof response.items === 'string') {
          try {
            formData.items = JSON.parse(response.items).map(item => ({
              name: item.name,
              quantity: item.quantity,
              price: item.price,
              subtotal: item.quantity * item.price
            }));
          } catch (e) {
            formData.items = [];
          }
        } else if (Array.isArray(response.items)) {
          formData.items = response.items.map(item => ({
            name: item.name,
            quantity: item.quantity,
            price: item.price,
            subtotal: item.quantity * item.price
          }));
        }
        
        return true;
      } else {
        ElMessage.error('加载订单数据失败');
        return false;
      }
    } catch (error) {
      console.error('加载订单数据失败:', error);
      ElMessage.error('加载订单数据失败');
      return false;
    } finally {
      loadingData.value = false;
    }
  };

  // 添加商品项
  const addItem = () => {
    if (!itemForm.name.trim()) {
      ElMessage.warning('请输入商品名称');
      return;
    }
    
    if (itemForm.quantity <= 0 || itemForm.price < 0) {
      ElMessage.warning('请输入有效的数量和价格');
      return;
    }

    formData.items.push({
      name: itemForm.name,
      quantity: itemForm.quantity,
      price: itemForm.price,
      subtotal: itemForm.quantity * itemForm.price
    });

    // 重置商品项表单
    itemForm.name = '';
    itemForm.quantity = 1;
    itemForm.price = 0;
  };

  // 移除商品项
  const removeItem = (index) => {
    formData.items.splice(index, 1);
  };

  // 更新商品项数量
  const updateItemQuantity = (index, value) => {
    if (value > 0) {
      formData.items[index].quantity = value;
      formData.items[index].subtotal = value * formData.items[index].price;
    }
  };

  // 更新商品项价格
  const updateItemPrice = (index, value) => {
    if (value >= 0) {
      formData.items[index].price = value;
      formData.items[index].subtotal = formData.items[index].quantity * value;
    }
  };

  // 计算订单总价
  const calculateTotal = () => {
    return formData.items.reduce((total, item) => total + item.subtotal, 0);
  };

  // 表单验证
  const validateForm = () => {
    if (!formData.customer_name.trim()) {
      ElMessage.warning('请输入客户姓名');
      return false;
    }

    if (!formData.customer_phone.trim()) {
      ElMessage.warning('请输入客户电话');
      return false;
    }

    if (formData.items.length === 0) {
      ElMessage.warning('请至少添加一个商品');
      return false;
    }

    return true;
  };

  // 提交表单
  const submitForm = async () => {
    if (!orderId.value) {
      ElMessage.error('订单ID无效');
      return false;
    }

    if (!validateForm()) {
      return false;
    }

    loading.value = true;
    try {
      // 准备提交数据
      const total_amount = calculateTotal();
      const submitData = {
        customer_name: formData.customer_name,
        customer_phone: formData.customer_phone,
        total_amount: total_amount,
        items: formData.items
      };

      const response = await orderApi.updateOrder(orderId.value, submitData);
      
      if (response && response.id) {
        ElMessage.success('订单更新成功');
        return true;
      } else {
        ElMessage.error('订单更新失败');
        return false;
      }
    } catch (error) {
      console.error('更新订单失败:', error);
      ElMessage.error('订单更新失败');
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 重置表单
  const resetForm = () => {
    orderId.value = null;
    formData.customer_name = '';
    formData.customer_phone = '';
    formData.order_time = new Date().toISOString();
    formData.items = [];
    
    itemForm.name = '';
    itemForm.quantity = 1;
    itemForm.price = 0;
  };

  return {
    formData,
    orderId,
    loading,
    loadingData,
    itemForm,
    loadOrderData,
    addItem,
    removeItem,
    updateItemQuantity,
    updateItemPrice,
    calculateTotal,
    submitForm,
    resetForm
  };
}